<template>
  <view class="container">
    <!-- 固定头部 -->
    <view class="head"
      style="background-color: #ffcc00; height: 180rpx; display:flex; position: fixed; top: 0; left: 0; right: 0; z-index: 999;">
      <view style="height: fit-content; margin-top: 15%; margin-left: 35%; font-size: 32rpx;">微信商城</view>
    </view>

    <!-- banner 放到 head 下方，非 fixed -->
    <view class="banner-wrapper" style="margin-top: 180rpx;">
      <swiper class="banner-swiper" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="500">
        <swiper-item v-for="(img, idx) in bannerList" :key="idx">
          <image :src="img" class="banner-img" mode="aspectFill" />
        </swiper-item>
      </swiper>
    </view>

    <!-- 医院选择与展示，放在banner下方、商品列表上方 -->

    <view class="hospital-section" v-if="hospitalList.length">
      <picker :range="hospitalList" range-key="hospitalName" @change="onHospitalChange">
        <view class="hospital-row">
          <text>医院：</text>
          <text class="hospital-selected">
            {{ selectedHospital ? selectedHospital.hospitalName : '请选择医院' }}
          </text>
          <text v-if="selectedHospital" class="hospital-info">
            （地址：{{ selectedHospital.hospitalAddress }}）
          </text>
        </view>
      </picker>
    </view>

    <!-- 内容区域 -->
    <view class="content-wrapper">
      <!-- 左侧分类列表 -->
      <view class="left-panel">
        <view v-for="category in categories" :key="category.id" class="button-item"
          :class="{ active: activeCategoryId === category.id }" @click="handleCategoryClick(category)">
          <text>{{ category.categoryName }}</text>
        </view>
      </view>

      <!-- 右侧内容 -->
      <view class="right-panel">
        <!-- 商品列表 -->
        <view class="service-list">
          <view 
            v-for="product in filteredProducts" 
            :key="product.id" 
            class="service-item" 
            :class="{ 'out-of-stock': product.status === '0' }"  
          >
            <!-- 缺货遮罩 -->
            <view v-if="product.status === '0'" class="out-of-stock-overlay">
              缺货
            </view>

            <!-- 商品主区，status 为 '0' 时点击无效 -->
            <view 
              class="service-main" 
              @click="product.status === '1' && handleProductClick(product)"  
            >
              <image :src="product.productImage" class="service-image" />
              <view class="service-info">
                <text class="service-name">{{ product.productName }}</text>
                <text class="service-price">¥{{ product.price }}</text>
                <text class="service-description">{{ product.description }}</text>
              </view>
            </view>

            <!-- 数量控制，只在 status==='1' 时显示 -->
            <view class="cart-controls" @click.stop>
              <template v-if="product.status === '1'">
                <button 
                  class="cart-btn" 
                  @click="removeFromCart(product)" 
                  v-if="getCartQuantity(product.id) > 0"
                >-</button>
                <text v-if="getCartQuantity(product.id) > 0" class="cart-qty">
                  {{ getCartQuantity(product.id) }}
                </text>
                <button class="cart-btn" @click="addToCart(product)">+</button>
              </template>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 悬浮购物车条 -->
    <view class="cart-bar">
      <!-- 只让图标可点击弹窗 -->
      <view style="position:relative;">
        <image src="../../../../../static/icons/购物车.png" class="cart-bar-icon" @click.stop="showCart = true" />
        <!-- 红点 -->
        <view class="cart-count" v-if="cartTotal > 0">{{ cartTotal }}</view>
      </view>
      <view class="cart-bar-amount">
        合计：<text class="cart-bar-price">¥{{cart.reduce((sum, item) => sum + item.price * item.quantity, 0).toFixed(2)
        }}</text>
      </view>
      <button class="cart-bar-pay-btn" :disabled="cart.length === 0" @click="goToPay">去支付</button>
    </view>

    <!-- 悬浮购物车按钮 -->
    <!-- <view class="cart-fab" @click="showCart = true">
      <image src="../../../../../static/icons/购物车.png" class="cart-icon" />
      <view class="cart-count" v-if="cart.length">{{cart.reduce((sum, item) => sum + item.quantity, 0)}}</view>
    </view> -->

    <!-- 购物车弹窗 -->
    <view v-if="showCart" class="cart-popup">
      <view class="cart-header">
        <view class="cart-title">购物车</view>
        <view class="header-buttons">
          <button class="clear-btn" @click="clearCart">清空</button>
          <button class="close-btn" @click="showCart = false">×</button>
        </view>
      </view>
      <view v-if="cart.length === 0" class="cart-empty">购物车为空</view>
      <view v-else class="cart-items-container">
        <view v-for="item in cart" :key="item.id" class="cart-item">
          <image :src="item.internalServiceImage || item.productImage" class="cart-item-img" />
          <text class="cart-item-name">{{ item.serviceName || item.productName }}</text>
          <view class="cart-item-controls">
            <button @click="removeFromCart(item)">-</button>
            <text>{{ item.quantity }}</text>
            <button @click="addToCart(item)">+</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 商品展示区和后续内容... -->
    <!-- ...existing code... -->
  </view>
  <!-- 获取手机号弹窗 -->
  <view v-if="showAuthModal" class="auth-modal">
    <view class="auth-modal-content">
      <view class="auth-modal-header">
        <text class="auth-modal-title">提示</text>
      </view>
      <view class="auth-modal-body">
        <text class="auth-modal-text">您还未登录，请先授权获取手机号</text>
      </view>
      <view class="auth-modal-footer">
        <button class="auth-modal-button auth-modal-button-cancel" @click="showAuthModal = false">
          取消
        </button>
        <button class="auth-modal-button auth-modal-button-confirm" open-type="getPhoneNumber"
          @getphonenumber="handleGetPhoneNumber">
          授权登录
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getCategory } from '@/api/product/category';
import { getProducts } from '@/api/product/product';
import { getShopBannerList } from '@/api/content/banner'
import { getHospitalAddressList } from '@/api/wxlogin/wxlogin'; // 导入接口
import { nextTick } from 'vue';
import { wxLogin, getOpenId } from '@/api/wxlogin/wxlogin';

const showAuthModal = ref(false);


const categories = ref([]);
const products = ref([]);
const activeCategoryId = ref(null);
const bannerList = ref([]);

// 购物车相关
const cart = ref([]);
const showCart = ref(false);

// 微信登录获取code
const wxLoginHandler = async () => {
  try {
    const loginRes = await new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          if (res.code) {
            resolve(res.code);
          } else {
            reject(new Error('登录失败'));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
    // 获取 openid
    const openIdRes = await getOpenId(loginRes);
    if (openIdRes.code === 200) {
      uni.setStorageSync('openid', openIdRes.data.openid);
    }
    return loginRes;
  } catch (err) {
    throw err;
  }
};

// 获取手机号回调
const handleGetPhoneNumber = async (e) => {
  if (e.detail.errMsg !== 'getPhoneNumber:ok') {
    uni.showToast({
      title: '获取手机号失败',
      icon: 'none'
    });
    return;
  }
  try {
    const loginCode = await wxLoginHandler();
    // 调用登录接口
    const res = await wxLogin({
      code: e.detail.code,
      loginCode: loginCode
    });
    if (res.code === 200) {
      uni.setStorageSync('isLoggedIn', true);
      uni.setStorageSync('userId', res.data.userId);
      uni.setStorageSync('phoneNumber', res.data.phoneNumber);
      uni.setStorageSync('userInfo', JSON.stringify({
        name: res.data.name,
        gender: res.data.gender,
        age: res.data.age,
        birthday: res.data.birthday,
        phoneNumber: res.data.phoneNumber
      }));
      isLoggedIn.value = true;
      showAuthModal.value = false;
      await nextTick();
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      });
    } else {
      throw new Error(res.msg || '获取手机号失败');
    }
  } catch (err) {
    uni.showToast({
      title: err.message || '登录失败',
      icon: 'none'
    });
  }
};

// 立即登录按钮点击（如需用到可直接调用）
const handleLoginClick = async () => {
  showAuthModal.value = true;
  await nextTick();
};
// 医院相关
const hospitalList = ref([]);
const selectedHospitalIndex = ref(null);
const selectedHospital = computed(() => {
  if (
    selectedHospitalIndex.value !== null &&
    hospitalList.value.length > 0
  ) {
    return hospitalList.value[selectedHospitalIndex.value];
  }
  return null;
});

// 计算属性：根据选中分类过滤商品
const filteredProducts = computed(() => {
  if (!activeCategoryId.value) return products.value;
  return products.value.filter(product => product.categoryId === activeCategoryId.value);
});

// 获取商品在购物车中的数量
const getCartQuantity = (productId) => {
  const item = cart.value.find(i => i.id === productId);
  return item ? item.quantity : 0;
};

// 增加商品到购物车
const addToCart = (product) => {
  const idx = cart.value.findIndex(i => i.id === product.id);
  if (idx > -1) {
    cart.value[idx].quantity += 1;
  } else {
    cart.value.push({ ...product, quantity: 1 });
  }
};

// 减少商品数量
const removeFromCart = (product) => {
  const idx = cart.value.findIndex(i => i.id === product.id);
  if (idx > -1) {
    if (cart.value[idx].quantity > 1) {
      cart.value[idx].quantity -= 1;
    } else {
      cart.value.splice(idx, 1);
    }
  }
};

// 购物车商品总数
const cartTotal = computed(() => cart.value.reduce((sum, item) => sum + item.quantity, 0));
const isLoggedIn = ref(uni.getStorageSync('isLoggedIn') || false);

// 处理分类点击
const handleCategoryClick = (category) => {
  activeCategoryId.value = category.id;
};

// 处理商品点击（跳转详情）
const handleProductClick = (product) => {
  // 字段名转换
  const service = {
    ...product,
    internalServiceImage: product.productImage,
    serviceName: product.productName,
  };
  // 购物车信息也传递过去
  uni.navigateTo({
    url: `/pages/customer-platform/index/menu/wxpay/serviceBooking?service=${encodeURIComponent(JSON.stringify(service))}&cart=${encodeURIComponent(JSON.stringify(cart.value))}`
});
};

// 处理返回按钮点击事件
const handleBack = () => {
  uni.navigateBack();
};

// 获取轮播图数据
const fetchBanner = async () => {
  try {
    const res = await getShopBannerList()
    if (res.code === 200 && Array.isArray(res.data)) {
      bannerList.value = res.data.map(item => item.url || item) // 兼容不同数据结构
    }
  } catch (err) {
    uni.showToast({ title: '获取banner失败', icon: 'none' })
  }
}

// 页面加载时获取数据
onLoad(async () => {
  try {
    const res = await getHospitalAddressList();
    if (res.code === 200 && Array.isArray(res.data)) {
      // 只保留每个医院名称的第一个数据
      const uniqueHospitals = [];
      const nameSet = new Set();
      for (const item of res.data) {
        if (!nameSet.has(item.hospitalName)) {
          uniqueHospitals.push(item);
          nameSet.add(item.hospitalName);
        }
      }
      hospitalList.value = uniqueHospitals;
      // 默认选中第一个
      if (hospitalList.value.length > 0) {
        selectedHospitalIndex.value = 0;
        // 修改这里：只存储医院名称而不是整个列表
        uni.setStorageSync('currentHospital', hospitalList.value[0].hospitalName);
        console.log('默认选中医院:', hospitalList.value[0].hospitalName);
      }
    }
  } catch (err) {
    uni.showToast({ title: '获取医院地址失败', icon: 'none' });
  }
  await fetchBanner()
  try {
    const categoryRes = await getCategory();
    if (categoryRes.code === 200) {
      categories.value = categoryRes.data;
      if (categories.value.length > 0) {
        activeCategoryId.value = categories.value[0].id;
      }
    }
    const productsRes = await getProducts();
    if (productsRes.code === 200) {
      products.value = productsRes.data;
    }
  } catch (err) {
    console.error('获取数据失败:', err);
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    });
  }
});

const onHospitalChange = (e) => {
  selectedHospitalIndex.value = Number(e.detail.value);
  // 保存选中的医院名称到本地存储
  if (hospitalList.value[e.detail.value]) {
    uni.setStorageSync('currentHospital', hospitalList.value[e.detail.value].hospitalName);
  }
};

const addressColumns = computed(() => {
  if (!selectedHospital.value) return [[], [], []];
  // 过滤出当前医院的所有房间数据
  const rooms = hospitalList.value.filter(
    h => h.hospitalName === selectedHospital.value.hospitalName
  );
  // 楼号、层号、房间号分别去重
  const buildings = [...new Set(rooms.map(r => r.building))].map(b => b + '号楼');
  const floors = [...new Set(rooms.map(r => r.floor))].map(f => f + '层');
  const roomNumbers = [...new Set(rooms.map(r => r.roomNumber))].map(r => r + '房间');
  return [buildings, floors, roomNumbers];
});

// 跳转支付页时传递三列数据
const goToPay = () => {
  if (!isLoggedIn.value) {
    handleLoginClick();
    return;
  }
  if (cart.value.length === 0) {
    uni.showToast({ title: '购物车为空', icon: 'none' });
    return;
  }

  // 新增：总金额校验，未满30元提示
  const totalAmount = cart.value.reduce((sum, item) => sum + item.price * item.quantity, 0);
  if (totalAmount < 30) {
    uni.showToast({ title: '满30元起送', icon: 'none' });
    return;
  }

  uni.navigateTo({
    url: `/pages/customer-platform/wxpay/payment/index?cart=${encodeURIComponent(JSON.stringify(cart.value))}&hospital=${encodeURIComponent(JSON.stringify(selectedHospital.value))}&addressColumns=${encodeURIComponent(JSON.stringify(addressColumns.value))}`
  });
}
// 清空购物车
const clearCart = () => {
  uni.showModal({
    title: '提示',
    content: '确定要清空购物车吗？',
    success: function (res) {
      if (res.confirm) {
        cart.value = [];
        uni.showToast({
          title: '购物车已清空',
          icon: 'success'
        });
      }
    }
  });
};
</script>

<style scoped lang="scss">
.container {
  padding: 32rpx;
  background-color: #fff;
  min-height: 100vh;
}

.banner-wrapper {
  width: 100%;
  height: 300rpx;
  margin-bottom: 24rpx;
  background: #fff;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  padding: 16rpx 0;
  display: flex;
  align-items: center;
  justify-content: center;

  .banner-swiper {
    width: 96%;
    height: 100%;
    border-radius: 20rpx;
    overflow: hidden;
  }

  .banner-img {
    width: 100%;
    height: 100%;
    display: block;
    border-radius: 20rpx;
  }
}

.content-wrapper {
  display: flex;
  margin-top: 0;
}

.left-panel {
  width: 150rpx;
  height: 80vh;
  padding: 16rpx;
  background-color: #fff;
  border-radius: 16rpx;
  margin-right: 16rpx;
  flex-shrink: 0;
  box-sizing: border-box;
  overflow-y: auto;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  border: 1rpx solid #eee;

  .button-item {
    padding: 16rpx 0;
    text-align: center;
    font-size: 28rpx;
    color: #666;
    border-bottom: 1rpx solid #eee;
    cursor: pointer;
    transition: all 0.2s ease;

    &:last-child {
      border-bottom: none;
    }

    &.active {
      color: #ffcc00;
      font-weight: bold;
      background-color: #f8f8f8;
    }

    &:hover {
      background-color: #f5f5f5;
    }
  }
}

.right-panel {
  width: 80%;
}

.service-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.service-item {
  height: 160rpx;
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 16rpx;
  position: relative;
}

.service-main {
  flex: 1;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.service-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.service-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 160rpx;
  padding: 10rpx 0;
  box-sizing: border-box;
}

.service-name {
  font-size: 28rpx;
  font-weight: bold;
  height: 40rpx;
  line-height: 40rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.service-price {
  font-size: 28rpx;
  color: #ff0000;
  height: 40rpx;
  line-height: 40rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.service-description {
  font-size: 28rpx;
  color: #666;
  height: 85rpx;
  line-height: 40rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}

.cart-controls {
  display: flex;
  align-items: center;
  margin-left: 16rpx;

  .cart-btn {
    width: 48rpx;
    height: 48rpx;
    border-radius: 50%;
    background: #ffcc00;
    color: #333;
    font-size: 32rpx;
    border: none;
    margin: 0 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .cart-qty {
    min-width: 32rpx;
    text-align: center;
    font-size: 28rpx;
    color: #333;
  }
}

.cart-count {
  position: absolute;
  top: 0rpx;
  right: 0rpx;
  background: #ff0000;
  color: #fff;
  border-radius: 50%;
  padding: 4rpx 10rpx;
  font-size: 24rpx;
  min-width: 32rpx;
  text-align: center;
  z-index: 10;
}

.cart-fab {
  position: fixed;
  right: 40rpx;
  bottom: 80rpx;
  width: 100rpx;
  height: 100rpx;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;

  .cart-icon {
    width: 60rpx;
    height: 60rpx;
  }


}

.cart-popup {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 100rpx; // 刚好在购物栏上方
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 32rpx;
  max-height: 50vh; // 设置最大高度为视窗高度的60%
  z-index: 10001;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column; // 使用弹性布局

  .cart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;
    flex-shrink: 0;

    .cart-title {
      font-size: 32rpx;
      font-weight: bold;
    }

    .header-buttons {
      display: flex;
      align-items: center;
      gap: 16rpx;

      .clear-btn {
        font-size: 28rpx;
        color: #666;
        background: none;
        border: none;
        padding: 0 16rpx;
        height: 60rpx;
        line-height: 60rpx;
      }

      .close-btn {
        width: 60rpx;
        height: 60rpx;
        line-height: 60rpx;
        text-align: center;
        font-size: 40rpx;
        color: #666;
        background: none;
        border: none;
        padding: 0;
        margin: 0;
      }
    }
  }

  .cart-empty {
    text-align: center;
    color: #999;
    font-size: 28rpx;
    margin: 40rpx 0;
  }

  // 商品列表区域添加滚动
  .cart-items-container {
    flex: 1; // 占据剩余空间
    overflow-y: auto; // 超出时显示滚动条
    padding-right: 16rpx; // 为滚动条预留空间
    margin-bottom: 24rpx; // 与底部按钮保持间距
  }

  .cart-item {
    display: flex;
    align-items: center;
    margin-bottom: 24rpx;
    padding: 12rpx 0;

    .cart-item-img {
      width: 80rpx;
      height: 80rpx;
      border-radius: 8rpx;
      margin-right: 16rpx;
      flex-shrink: 0; // 防止图片被压缩
    }

    .cart-item-name {
      font-size: 28rpx;
      color: #333;
      flex: 1;
    }

    .cart-item-controls {
      display: flex;
      align-items: center;
      flex-shrink: 0; // 防止控制按钮被压缩
    }
  }

  .cart-footer {
    margin-top: auto;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    flex-shrink: 0;
    padding-top: 20rpx;
    border-top: 1rpx solid #eee;
  }
}

.cart-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  z-index: 9999;
  padding: 0 32rpx;

  .cart-bar-icon {
    width: 60rpx;
    height: 60rpx;
    margin-right: 24rpx;
  }

  .cart-bar-amount {
    flex: 1;
    font-size: 32rpx;
    color: #333;

    .cart-bar-price {
      color: #ff0000;
      font-weight: bold;
      margin-left: 8rpx;
    }
  }

  .cart-bar-pay-btn {
    background: #ffcc00;
    color: #333;
    font-size: 32rpx;
    border-radius: 40rpx;
    padding: 16rpx 48rpx;
    border: none;
    margin-left: 24rpx;
    opacity: 0.8;
  }
}

.hospital-section {
  margin-bottom: 32rpx;
  padding: 24rpx;
  background: #fffbe6;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(255, 204, 0, 0.08);

  .hospital-row {
    display: flex;
    align-items: center;
    font-size: 30rpx;
    color: #333;

    .hospital-selected {
      margin: 0 16rpx;
      color: #ff9900;
      font-weight: bold;
    }

    .hospital-info {
      color: #666;
      margin-left: 8rpx;
      font-size: 28rpx;
    }
  }
}

.auth-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;

  .auth-modal-content {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 32rpx;
    width: 80%;
    max-width: 600rpx;

    .auth-modal-header {
      font-size: 32rpx;
      font-weight: bold;
      margin-bottom: 16rpx;
    }

    .auth-modal-body {
      font-size: 28rpx;
      margin-bottom: 32rpx;
    }

    .auth-modal-footer {
      display: flex;
      justify-content: space-between;

      .auth-modal-button {
        padding: 10rpx 20rpx;
        border-radius: 8rpx;
        font-size: 28rpx;
        cursor: pointer;

        &-cancel {
          background-color: #f0f0f0;
          color: #333333;
        }

        &-confirm {
          background-color: #ffcc00;
          color: #333333;
        }
      }
    }
  }
}
</style>
